package pers.qianyu.month_202012.date_20201210;

import org.junit.*;

import java.util.*;

/**
 * [同 date_20201112]
 * 51. N 皇后
 * https://leetcode-cn.com/problems/n-queens/
 *
 * @author mizzle rain
 * @date 2020-12-10 15:26
 */
public class SolveNQueens {
    List<List<String>> res = new ArrayList<>();

    public List<List<String>> solveNQueens(int n) {
        char[][] track = new char[n][n];
        for (int i = 0; i < track.length; i++) {
            Arrays.fill(track[i], '.');
        }
        recur(track, n - 1);
        return res;
    }

    private void recur(char[][] track, int row) {
        if (row < 0) {
            res.add(arrayToList(track));
            return;
        }
        for (int k = 0; k < track.length; k++) {
            if (isInvalid(track, row, k)) {
                continue;
            }
            track[row][k] = 'Q';
            recur(track, row - 1);
            track[row][k] = '.';
        }
    }

    private boolean isInvalid(char[][] track, int i, int j) {
        int len = track.length;
        for (int k = 0; k < len; k++) {
            if (track[i][k] == 'Q') {
                return true;
            }
            if (track[k][j] == 'Q') {
                return true;
            }
        }
        int p1 = i + 1, p2 = j + 1;
        while (p1 < len && p2 < len) {
            if (track[p1][p2] == 'Q') {
                return true;
            }
            p1++;
            p2++;
        }
        p1 = i - 1;
        p2 = j - 1;
        while (p1 >= 0 && p2 >= 0) {
            if (track[p1][p2] == 'Q') {
                return true;
            }
            p1--;
            p2--;
        }
        p1 = i + 1;
        p2 = j - 1;
        while (p1 < len && p2 >= 0) {
            if (track[p1][p2] == 'Q') {
                return true;
            }
            p1++;
            p2--;
        }
        p1 = i - 1;
        p2 = j + 1;
        while (p1 >= 0 && p2 < len) {
            if (track[p1][p2] == 'Q') {
                return true;
            }
            p1--;
            p2++;
        }
        return false;
    }

    private List<String> arrayToList(char[][] arr) {
        ArrayList<String> res = new ArrayList<>();
        for (char[] chars : arr) {
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < chars.length; i++) {
                builder.append(chars[i]);
            }
            res.add(builder.toString());
        }
        return res;
    }

    @Test
    public void test1() {
        List<List<String>> res = new SolveNQueens().solveNQueens(4);
        printResult(res);
    }

    private void printResult(List<List<String>> res) {
        for (List<String> r : res) {
            r.forEach(System.out::println);
            System.out.println("---------------------");
        }
    }
}